<template>
  <view class="component-container" :class="{ grey: props.cart.length === 0 }">
    <view class="left">
      <view class="count" @click="clickCart">
        <image src="./cart.png" class="cart-image" />
        <view class="document-count" v-show="count > 0">{{ count }}</view>
      </view>
      <view class="price">
        <span class="total-price">¥{{ totalPrice.toFixed(2) }}</span>
        <span class="additional-fee">{{ currentAdditionalFeeDescription }}</span>
      </view>
    </view>
    <view class="to-settlement" @click="toConfirmOrderPage">去结算</view>
  </view>
  <cart-list v-model:visible="hideList" :data="props.cart" :bottom-safe-area="cartBottomSafeArea" />
</template>

<script setup lang="ts">
import { CartItem } from '@/types/entity/ShoppingCart'
import { ref, computed, getCurrentInstance, type Ref, inject } from 'vue'
import CartList from './cart-list/index.vue'
import StyleSizeOperation from '@/utils/StyleSizeOperation'
import $store from '@/store'
import type { ShopInfo } from '@/types/response/shop'
import VarUtils from '@/utils/VarUtils'
import UrlUtils from '@/utils/UrlUtils'
import { $modal } from '@/plugins'
import { ReceivingMethod } from '@/enum/ReceivingMethod'
interface Point {
  x: number
  y: number
}
const props = defineProps({
  cart: {
    type: Object as () => CartItem[],
    default: [] as CartItem[]
  },
  cartPosition: {
    type: Object as () => Point,
    default: {} as Point
  }
})

const emits = defineEmits<(e: 'update:cartPosition', newVal: Point) => void>()

// 显示列表
const hideList = ref(false)

// 获取购物车的位置
const instance = getCurrentInstance() // 获取组件实例

// 获取微信小程序dom元素
let query = uni.createSelectorQuery().in(instance)
query
  .select('.cart-image')
  .fields({ dataset: true, rect: true, id: true }, (res: any) => {
    emits('update:cartPosition', { x: res.left, y: res.top })
  })
  .exec()
// 动态计算总价
const totalPrice = computed(() => {
  return props.cart.reduce((total, item) => {
    return total + item.price
  }, 0)
})
// 动态计算总数量
const count = computed(() => {
  return props.cart.reduce((total, item) => {
    return total + item.count
  }, 0)
})
// 点击购物车时
function clickCart() {
  // 当购物车里面没有东西时（此时灰色）,不响应
  if (props.cart == null || props.cart.length === 0) return
  hideList.value = !hideList.value
}
// 获取样式
const cartBottomSafeArea = ref<string>()
query
  .select('.component-container')
  .fields({ dataset: true, rect: true, id: true, computedStyle: ['height', 'bottom'] }, (res: any) => {
    cartBottomSafeArea.value = StyleSizeOperation.summation(res.bottom, res.height)
  })
  .exec()

// 获取父组件向下共享的店铺信息
const shopInfo = inject<Ref<ShopInfo>>('shopInfo')
// 监听是否已经可以去创建订单（看是否满足起购价）
let isMeetMinimumPrice = computed(() => {
  if (shopInfo == null || shopInfo.value == null) return false
  return totalPrice.value >= shopInfo?.value.minimumDeliveryAmount
})
// 获取额外费用描述
const currentAdditionalFeeDescription = ref('')
function refreshAdditionalFeeDescription() {
  const currentReceivingMethod = $store.shop.receivingMethod.getValue()
  let packingChargeDesc = ''
  if ((shopInfo?.value?.packingFee ?? 0) > 0 && currentReceivingMethod !== ReceivingMethod.SHOP_EAT) {
    packingChargeDesc = '打包费: ¥' + (shopInfo?.value?.packingFee ?? 0)
  }
  let deliveryFeeDesc = ''
  if (shopInfo?.value?.deliveryFee !== 0 && currentReceivingMethod === ReceivingMethod.DELIVERY) {
    deliveryFeeDesc = '配送费: ¥' + (shopInfo?.value?.deliveryFee ?? 0)
  }
  const content = `${packingChargeDesc}  ${deliveryFeeDesc}`
  currentAdditionalFeeDescription.value = content.trim() === '' ? '无需额外费用' : `另需 ${content}`
}
// 监听配送方式改变（自提/配送）
$store.shop.receivingMethod.watch((newVal) => refreshAdditionalFeeDescription(), true)
// 监听shopInfo有数据
VarUtils.await<ShopInfo, ShopInfo>(
  shopInfo!,
  (shopInfo) => shopInfo.value,
  () => refreshAdditionalFeeDescription()
)
// 去确认订单页函数
function toConfirmOrderPage() {
  if (!isMeetMinimumPrice.value) {
    $modal.toastMsg('未达到要求的最低下单价')
    return
  }
  // 收集好数据
  const receivingMethodRef = $store.shop.receivingMethod.getRef()
  const shopId = shopInfo?.value.id
  if (receivingMethodRef == null || shopId == null) return
  const options = {
    receivingMethod: receivingMethodRef.value,
    shopId
    // longitude: shopInfo?.value.longitude,
    // latitude: shopInfo?.value.latitude
  }
  uni.navigateTo({
    url: `/pages/order-pages/confirm/index` + UrlUtils.encodeParams(options)
  })
}
</script>

<style scoped lang="scss">
$height: 120rpx;
$right-button-height: $height * 0.6;
$cart-margin-size: 5vw;

/* 购物车为空 */
.grey {
  filter: grayscale(100%);
  filter: gray;
}

.component-container {
  position: fixed;
  right: 0;
  bottom: $cart-margin-size;
  left: 0;
  z-index: 1001;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 0 auto;
  width: 100vw - $cart-margin-size * 2;
  height: $height;
  border-radius: 60rpx;
  color: #fff;
  background-color: #212526;
  box-sizing: border-box;

  .left {
    display: flex;
    align-items: center;

    .price {
      display: flex;
      flex-direction: column;

      .total-price {
        font-size: 35rpx;
        font-weight: 700;
      }

      .additional-fee {
        font-size: 21rpx;
      }
    }

    .count {
      position: relative;
      margin-right: $right-button-height * 0.5;
      margin-left: $right-button-height * 0.7;

      .cart-image {
        width: 50rpx;
        height: 50rpx;
      }

      .document-count {
        position: absolute;
        top: -15rpx;
        right: -15rpx;
        min-width: 35rpx;
        height: 35rpx;
        font-size: 25rpx;
        border-radius: 50%;
        text-align: center;
        color: #fff;
        background-color: red;
        line-height: 35rpx;
      }
    }
  }

  .to-settlement {
    margin-right: ($height - $right-button-height) * 0.5;
    padding: 0 40rpx;
    height: $right-button-height;
    font-size: 30rpx;
    border-radius: $right-button-height * 0.5;
    color: black;
    background-color: #f9d450;
    line-height: $right-button-height;
  }
}
</style>
